// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class HorseCtrl extends cc.Component {

    @property
    moveSpeed: number = 10;

    @property(cc.Animation)
    animation: cc.Animation = null;

    @property
    farDistance: number = 2000;
    


    
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        this.moveSpeed = 0;
        cc.game.once('RaceStart', () => {
            this.raceStart();
        });
        cc.game.once('StopRun', () => {
            this.moveSpeed = 0;
            this.animation.stop();
            this.unscheduleAllCallbacks();
        });
    }


    protected onDestroy(): void {
        
    }

    raceStart(){
        let animState = this.animation.play(); // 播放动画
        animState.speed = 3;
        //this.moveSpeed = (Math.random() * 50) + 200;
        this.schedule(() => {
            //if(Math.random() > 0.5){
                this.moveSpeed = (Math.random() * 200) + 1800;
            //}
        }, 1, 100,0);
    }

    update (dt) {
        if(this.node.x > 59700){
            this.scheduleOnce(() => {

                cc.game.emit('RaceEnd');
            }, 2);
            cc.game.emit('StopRun');
            //cc.game.pause();
            //cc.director.pause();
        }
        this.node.x += this.moveSpeed * dt;
        if(this.node.x > this.farDistance){
            this.moveSpeed = 0;
        }else{
            //this.moveSpeed = (Math.random() * 1000) + 100;
            //this.moveSpeed =  600;
        }
        
    }
}
